<template>
     <el-form :inline="true" :model="form" label-width="auto" style="padding: 10px;">
<!--        <el-form-item label="编码">-->
<!--                  <el-input v-model="form.deviceId" :disabled="action!='add'"/>-->
<!--                </el-form-item>-->
        <el-form-item label="名称">
          <el-input v-model="form.name"/>
        </el-form-item>
       <el-form-item label="资产类型">
         <el-select v-model="form.assetTypeId" placeholder="资产类型">
           <el-option  v-for="item in dict.assetType" :label="item.label" :value="item.value" :key="item.value"/>
         </el-select>
       </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark"  style="width: 700px;"/>
        </el-form-item>
       <div>
       <el-form-item label="关联终端">
         <ul>
           <li v-for="(o,index) in form.terminalList" :key="o" class="text item">
             {{o.name + '('+o.code+')' }}
             <el-button type="danger" link @click="handleRemoveTerminal(index)"><el-icon><Close/></el-icon></el-button>
             </li>
         </ul>
         <el-button @click="handleTerminalDialog">关联</el-button>
       </el-form-item>
       </div>

       <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleTabClick">
         <el-tab-pane label="数据点" name="points">
           <el-table :data="signals" style="width: 100%;">
             <el-table-column prop="terminalName" label="终端" />
             <el-table-column prop="code" label="编码" />
             <el-table-column prop="name" label="名称"  />
             <el-table-column prop="unit" label="单位"/>
             <el-table-column prop="value" label="当前值">
               <template #default="scope">
                 <el-tooltip v-if="scope.row.alarmMsg&&scope.row.alarmMsg.length>0"
                             :content="scope.row.alarmMsg"
                             placement="bottom"
                             effect="light">
                   <el-text type="danger">{{scope.row.value}}{{scope.row.unit}}</el-text>
                 </el-tooltip>
                 <el-text v-else-if="scope.row.value" type="primary">{{scope.row.value}}{{scope.row.unit}}</el-text>
                 <el-text v-else>-</el-text>
               </template>
             </el-table-column>
           </el-table>
         </el-tab-pane>
         <el-tab-pane label="告警" name="alarm">
           <el-table :data="alarmObj.data" style="width: 100%;">
             <el-table-column prop="id" label="事件ID" />
             <el-table-column prop="name" label="名称" />
             <el-table-column prop="startTime" label="时间"/>
             <el-table-column prop="confirmed" label="确认">
               <template #default="scope">
                 {{scope.row.confirmed?'是':'否'}}
               </template>
             </el-table-column>
             <el-table-column prop="cleared" label="清除">
               <template #default="scope">
                 {{scope.row.cleared?'是':'否'}}
               </template>
             </el-table-column>
             <el-table-column prop="additionalInfo" label="附加信息">
               <template #default="scope">
                 <el-text type="danger">{{scope.row.additionalInfo}}</el-text>
               </template>
             </el-table-column>
             <el-table-column label="操作" align="center">
               <template #default="scope">
                 <el-button link type="primary" @click="handleAlarmEdit(scope.row)">处理</el-button>
               </template>
             </el-table-column>
           </el-table>
           <pagination v-model:size="alarmObj.query.pageSize" v-model:page="alarmObj.query.pageNum" :total="alarmObj.total" @pagination="loadAlarmList" />
         </el-tab-pane>
         <el-tab-pane label="事件" name="eventLog">
           <el-form :inline="true" label-width="auto" style="padding: 10px;">
             <el-form-item label="消息">
               <el-input v-model="sendMsg" style="width: 700px;"/>
               <el-button @click="handleSendMsg">发送</el-button>
             </el-form-item>

           </el-form>


           <el-table :data="eventLogObj.data" style="width: 100%;">
             <el-table-column type="selection" width="55" />
             <el-table-column prop="id" label="事件ID" />
             <el-table-column prop="name" label="名称" />
             <el-table-column prop="tran.sceneName" label="场景" />
             <el-table-column prop="success" label="是否成功">
               <template #default="scope">
                 <el-text v-if="scope.row.success" type="success">成功</el-text>
                 <el-text v-else type="danger">失败</el-text>
               </template>
             </el-table-column>
             <el-table-column prop="eventTime" label="时间"/>
             <el-table-column prop="tran.actionType" label="动作类型"/>
             <el-table-column prop="remark" label="参数"/>
           </el-table>
           <pagination v-model:size="eventLogObj.query.pageSize" v-model:page="eventLogObj.query.pageNum" :total="eventLogObj.total" @pagination="loadEventLogList" />
         </el-tab-pane>
       </el-tabs>



          <div style="text-align:center;margin: 10px auto;">
            <el-button type="primary" @click="handleAdd">保存</el-button>
            <el-button @click="handleCancel">取消</el-button>
          </div>
      </el-form>
  <dwin ref="terminalDialog" :width="860" :url="'/view/terminal/selector.vue'" :title="'新增终端'" @onclose="handleTerminalClose"></dwin>
  <dwin ref="alarmDialog" :width="1024" :url="'/view/alarm/edit.vue'" :title="'告警详情'" @onclose="handleAlarmClose"></dwin>
</template>
<script>
    import{reactive, ref} from 'vue'
    import {add,edit,listSignals,assetTypes} from '/http/device.js'
    import Dwin from "../../component/dwin.vue";
    import {useDict} from '/http/options.js'
    import WeekPlan from "../../component/weekPlan.vue";
    import Pagination from "../../component/pagination.vue";
    import useWebsocket from '../../public/websocket.js';
    import {listByDeviceId as queryAlarmList} from '../../http/alarm.js'
    import {listByDeviceId as queryEventLogList} from '../../http/event-log.js'

    const {ElMessage,ElMessageBox} = ElementPlus;
    export default {
      components: {Pagination, Dwin,WeekPlan},
        props:{
          initParams:Object
        },
        setup(props,context){
          const dict = ref({});
          const activeName = ref('points')
          useDict(dict,'fluxData,storePolicy,alarmPolicy');
          assetTypes().then(res=>{
            dict.value['assetType'] = res.data.data
          })
            const form=reactive({
              deviceId:null,
              name:'',
              assetTypeId:'',
              category:'',
              remark:'',
              terminalList:[]
            })
          const signalListRef = ref(null);

          const handleAdd = ()=>{
              if(action.value=='add'){
                add(form).then(res=> {
                  response(res,context)
                });
              }else{
                edit(form).then(res=> {
                  response(res,context)
                });
              }
          }


          const handleCancel = ()=>{
              context.emit('close',false)
          }
          const action = ref('edit');
          const dialog = ref(null);


          const handleClose1 = (data)=>{
            data.forEach(item=>{
              form.signalList.push(item);
            })

          }


          function onSelectSignal(){
            dialog.value.open(form.signalList);
          }

          //==============新增终端=================
          const terminalDialog = ref(null);
          const handleTerminalDialog =()=>{
            console.log( terminalDialog)
            terminalDialog.value.open()
          }
          const handleTerminalClose = (data)=>{
            if(!data)return;
            const temp = [];
            data.forEach(item=>{
              if(form.terminalList.findIndex(t=>t.code===item.code)<0){
                temp.push(item);
              }
            })
            form.terminalList.push(...temp)
          }
          //=============数据点===============
          const signals = ref([]);
          const ws = useWebsocket('ws://'+window.location.hostname+env.baseURL+"/ws/stiot/"+utils.readCookie("SOLONID"));
          ws.on('message',data=>{
            data.playload.terminals.forEach(t=>{
                signals.value.forEach(item=>{
                  if(item.terminalCode === t.code){
                    Object.keys(t.data).forEach(k=>{
                      if(item.code===k){
                        item.value = t.data[k];
                      }
                    })
                  }
              })
            })
          })


          //============================告警列表==============================
          const alarmDialog = ref(null)
          const  alarmObj = reactive({
            data:[],
            total:0,
            query:{
              pageSize:10,
              pageNum:1,
            }
          })
          const loadAlarmList=()=>{
            queryAlarmList(Object.assign(alarmObj.query,{deviceId:form.deviceId})).then(res=>{
              alarmObj.data = res.data.data;
              alarmObj.total = parseInt(res.data.total);
            })
          }
          const handleAlarmEdit = (row)=>{
            alarmDialog.value.open(row);
          }
          const handleAlarmClose = ()=>{
            loadAlarmList()
          }
          //========================事件列表================================
          const  eventLogObj = reactive({
            data:[],
            total:0,
            query:{
              pageSize:10,
              pageNum:1,
            }
          })
          const loadEventLogList=()=>{
            queryEventLogList(Object.assign(eventLogObj.query,{deviceId:form.deviceId})).then(res=>{
              eventLogObj.data = res.data.data;
              eventLogObj.total = parseInt(res.data.total);
              console.log(eventLogObj)
            })
          }

          const handleRemoveTerminal = (index)=>{
            form.terminalList.splice(index,1)
          }

          const terminals = ref([]);
          onMounted(()=>{
            if(props.initParams){
              Object.assign(form,props.initParams)
              if(!form.terminalList){
                form.terminalList = [];
              }
              listSignals(form.deviceId).then(res=>{
                signals.value = res.data.data

                signals.value.forEach(item=>{
                  if(terminals.value.indexOf(item.terminalCode)<0){
                    terminals.value.push(item.terminalCode)
                  }
                })
                //加载
                loadEventLogList();
                loadAlarmList();

                ws.on('open',()=>{
                  ws.send({
                    command: "setPageModel",
                    params: {
                      terminals: terminals.value,
                      queries: []
                    }
                  })
                })
                ws.connect();
              })
              action.value= 'edit'
            }else{
              action.value= 'add'
            }
          })


          return{
            form,handleAdd,handleCancel,action,dialog,onSelectSignal,handleClose1,dict,activeName
            ,handleTerminalClose,handleTerminalDialog,terminalDialog
            ,signals,eventLogObj
            ,alarmObj,alarmDialog,handleAlarmEdit,handleAlarmClose,handleRemoveTerminal
          }
        }
    }
</script>

<style scoped>
.el-form .el-select {
  width: 192px; /* 或者根据需要设置其他宽度 */
}
.vertical-radio .el-radio {
  display: block;
  margin-bottom: 10px; /* 可根据需要调整间距 */
}
.header {
  font-size: 16px;
  border-top: #f0f0f0 solid 1px;
  margin: 0;
  box-shadow: 2px 2px 4px rgba(0,0,0,0.1);
}
</style>